package com.bigfish.gbs.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.bigfish.gbs.dto.Result;
import com.bigfish.gbs.entity.User;
import com.bigfish.gbs.enums.AlipayEnum;
import com.bigfish.gbs.service.AlipayService;
import com.bigfish.gbs.util.ResultUtil;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author Joycessh
 * @Description
 * @Date 12/25/18 2:25 AM
 */
@Api(value = "Alipay", description = "支付宝")
@RequestMapping("/order/")
@RestController
public class AlipayController extends BasicAction {

    private final static Logger LOGGER = LoggerFactory.getLogger(AlipayController.class);

    @Autowired
    private AlipayService alipayService;

    /**
     * 方法说明
     * @author Joycessh
     * @param map
     * @return com.bigfish.gbs.dto.Result
     * @date 12/25/18 9:34 AM
     */
    @ApiOperation(value = "pay接口")
    @PostMapping("pay.do")
    public Result pay(@RequestBody HashMap<String, String> map){
        String userId = map.get("userId");
        Long orderId = Long.parseLong(map.get("orderId"));
        System.out.println(userId);
        System.out.println(orderId);
        if(userId ==null){
            return ResultUtil.retParams(1000, "用户账号为空");
        }

        return alipayService.pay(orderId, userId);
    }

    /**
     * 回调
     * @author Joycessh
     * @param request
     * @return java.lang.Object
     * @date 12/25/18 3:10 AM
     */
    @ApiOperation(value = "回调方法")
    @RequestMapping("alipay_callback.do")
    public Object alipayCallback(HttpServletRequest request){
        Map<String,String> params = Maps.newHashMap();

        Map requestParams = request.getParameterMap();
        for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for(int i = 0 ; i <values.length;i++){

                valueStr = (i == values.length -1)?valueStr + values[i]:valueStr + values[i]+",";
            }
            params.put(name,valueStr);
        }
        LOGGER.info("支付宝回调,sign:{},trade_status:{},参数:{}",params.get("sign"),params.get("trade_status"),params.toString());

        //非常重要,验证回调的正确性,是不是支付宝发的.并且呢还要避免重复通知.

        params.remove("sign_type");
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());

            if(!alipayRSACheckedV2){
                return ResultUtil.retParams(1000,"非法请求,验证不通过,再恶意请求我就报警找网警了");
            }
        } catch (AlipayApiException e) {
            LOGGER.error("支付宝验证回调异常",e);
        }

        //todo 验证各种数据


        //
        Result result  = alipayService.aliCallback(params);
        if(result.getCode() == 2000){
            return AlipayEnum.TRADE_STATUS_TRADE_SUCCESS;
        }
        return AlipayEnum.TRADE_STATUS_TRADE_FAILED;
    }

    /**
     * 轮询 查询  支付状态
     * @author Joycessh
     * @param userId
	 * @param orderId
     * @return java.lang.Boolean
     * @date 12/25/18 3:27 AM
     */
    @RequestMapping("query_order_pay_status.do")
    @ResponseBody
    public Boolean queryOrderPayStatus(String userId, Long orderId){

        Result result = alipayService.queryOrderPayStatus(userId,orderId);
        if(result.getCode() == 2000){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
